package com.nbjtjc.safe.wps.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.ObjectUtil;
import com.nbjtjc.safe.mapper.sys.SysFileMapper;
import com.nbjtjc.safe.mapper.sys.SysUserMapper;
import com.nbjtjc.safe.model.sys.SysFile;
import com.nbjtjc.safe.model.sys.SysUser;
import com.nbjtjc.safe.util.MyShiroUtils;
import com.nbjtjc.safe.wps.config.Context;
import com.nbjtjc.safe.wps.dto.*;
import com.nbjtjc.safe.wps.util.WpsUtil;
import com.nbjtjc.safe.wps.util.file.FileUtil;
import com.nbjtjc.safe.wps.util.upload.ResFileDTO;
import com.nbjtjc.safe.wps.util.upload.oss.OSSUtil;
import org.mapstruct.ap.shaded.freemarker.cache.StrongCacheStorage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.util.*;

@Service
public class WpsFileService {

    @Autowired
    private SysFileMapper sysFileMapper;

    @Autowired
    private SysUserMapper userMapper;
    @Value("${aliyun.oss.domain}")
    private String ossUrlPrefix;

    @Value("${wps.appid}")
    private String wpsAppId;

    @Value("${wps.redirectKey}")
    private String redirectKey;

    @Value("${wps.redirectValue}")
    private String redirectValue;

    @Autowired
    private WpsUtil wpsUtil;

    @Autowired
    private OSSUtil ossUtil;

    public Map<String, Object> getFileInfo(String _w_userid, String _w_fileid) {
        Map<String, Object> result = new HashMap<>();

        SysFile sysFile = sysFileMapper.selectByPrimaryKey(NumberUtil.parseInt(_w_fileid));

        if (ObjectUtil.isNull(sysFile)) {
            return result;
        }

        String downloadUrl = ossUrlPrefix + "/" + sysFile.getPath();
        System.out.println("wps 下载文件路径");
        UserAclBO userAclBO= new UserAclBO();
        userAclBO.setRename(1);
        userAclBO.setHistory(1);
        FileDTO file = new FileDTO(_w_fileid, sysFile.getFileName(), 1, sysFile.getSize()
                , sysFile.getUserId().toString(), sysFile.getCreateTime().getTime()
                , downloadUrl,userAclBO,new WatermarkBO());

        result.put("file",file);
        SysUser sysUser=userMapper.selectByUserId(NumberUtil.parseInt(_w_userid));
        UserDTO user=new UserDTO();
        user.setAvatar_url("https://nbjtjcsafe360.oss-cn-beijing.aliyuncs.com/logo.jpeg");
        user.setId(_w_userid);
        user.setPermission("write");
        //todo 更具审核状态判断返回是write还是read
        user.setName(sysUser.getUsername());
        result.put("user",user);
        return result;
    }

    public Map<String,Object> getViewUrl(int fileId,int userId){
        Map<String,Object> result=new HashMap<>();
        SysFile sysFile=sysFileMapper.selectByPrimaryKey(fileId);
        if(ObjectUtil.isNotNull(sysFile)){
            Map<String,String> values=new HashMap<>();
            String fileName=sysFile.getFileName();
            String fileType= FileUtil.getFileTypeByName(fileName);
            UUID randomUUID=UUID.randomUUID();
            String uuid=randomUUID.toString().replace("-","");
            values.put("_w_appid",wpsAppId);
            values.put("_w_userid",sysFile.getUserId().toString());
            values.put("_w_fileid",fileId+"");
            values.put("_w_tokentype","1");
            values.put(redirectKey,redirectValue);

            String wpsUrl=wpsUtil.getWpsUrl(values,fileType,fileId+"");

            result.put("token",uuid);
            result.put("wpsUrl",wpsUrl);
            return result;
        }
        return null;
    }


    @Transactional
    public Map<String,Object> fileSave(MultipartFile mFile,String userId){
        Map<String,Object> result=new HashMap<>();
        String fileId= Context.getFileId();
        SysFile oldFile=sysFileMapper.findById(NumberUtil.parseInt(fileId));
        if(oldFile.getFileId()==0){
            oldFile.setFileId(oldFile.getfId());
        }
        oldFile.setHistory(1);
        sysFileMapper.updateByPrimaryKeySelective(oldFile);
        ResFileDTO resFileDTO=ossUtil.uploadMultipartFile(mFile);
        System.out.println(resFileDTO.toString());
        SysFile newFile=new SysFile();
        BeanUtil.copyProperties(oldFile,newFile);
        newFile.setfId(null);
        newFile.setVersion(oldFile.getVersion()+1);
        newFile.setPath(resFileDTO.getFilePath());
        newFile.setSize((int)resFileDTO.getFileSize());
        newFile.setModifier(NumberUtil.parseInt(userId));
        newFile.setModifyTime(new Date());
        newFile.setHistory(0);
        sysFileMapper.insertSelective(newFile);
        FileDTO fileInfo=new FileDTO();
        fileInfo.setId(newFile.getfId().toString());
        fileInfo.setDownload_url(resFileDTO.getFileUrl());
        fileInfo.setName(newFile.getFileName());
        fileInfo.setSize((int)resFileDTO.getFileSize());
        fileInfo.setVersion(newFile.getVersion());
        result.put("file",fileInfo);
        return result;
    }


    private int getWpsFatherId(String fileId){

        return 0;
    }

    public void renameFile(String fileName,String userId){
        String fileId=Context.getFileId();
        SysFile sysFile=sysFileMapper.selectByPrimaryKey(NumberUtil.parseInt(fileId));
        if(sysFile!=null){
            sysFile.setFileName(fileName);
            sysFileMapper.updateByPrimaryKeySelective(sysFile);
        }
    }

    public Map<String,Object> fileHistory(FileReqDTO fileReqDTO){
        Map<String,Object> result=new HashMap<>();
        List<FileHisDTO>  fileHisDTOList=new ArrayList<>();
        SysFile sysFile=sysFileMapper.selectByPrimaryKey(NumberUtil.parseInt(fileReqDTO.getId()));
        if(ObjectUtil.isNotNull(sysFile)&&sysFile.getFileId()>0
        &&sysFile.getVersion()>0){
            List<SysFile> sysFiles=sysFileMapper.findByFileId(sysFile.getFileId(),sysFile.getVersion());
            System.out.println(sysFiles.size());
            sysFiles.forEach(oldFile->{
                FileHisDTO fileHisDTO=new FileHisDTO();
                fileHisDTO.setId(oldFile.getfId().toString());
                fileHisDTO.setName(oldFile.getFileName());
                fileHisDTO.setVersion(oldFile.getVersion());
                fileHisDTO.setSize(oldFile.getSize());
                fileHisDTO.setDownload_url(ossUrlPrefix + "/" + oldFile.getPath());
                fileHisDTO.setCreate_time(oldFile.getCreateTime().getTime()/1000);
                if(ObjectUtil.isNotNull(oldFile.getModifyTime())){
                    fileHisDTO.setModify_time(oldFile.getModifyTime().getTime()/1000);
                }else{
                    fileHisDTO.setModify_time(oldFile.getCreateTime().getTime()/1000);
                }
                UserDTO creator = new UserDTO();
                creator.setId(oldFile.getUserId().toString());
                creator.setAvatar_url("https://nbjtjcsafe360.oss-cn-beijing.aliyuncs.com/logo.jpeg");
                creator.setName(userMapper.findNameByUserId(oldFile.getUserId()));
                UserDTO modifier = new UserDTO();
                modifier.setId(oldFile.getModifier().toString());
                modifier.setAvatar_url("https://nbjtjcsafe360.oss-cn-beijing.aliyuncs.com/logo.jpeg");
                modifier.setName(userMapper.findNameByUserId(oldFile.getModifier()));
                fileHisDTO.setCreator(creator);
                fileHisDTO.setModifier(modifier);
                fileHisDTOList.add(fileHisDTO);
            });
        }
        result.put("histories",fileHisDTOList);
        System.out.println(fileHisDTOList.toString());
        return result;
    }
}
